package cloud.zhixinglu.www.spring.boot.paho.mqtt.mqtt;

import cloud.zhixinglu.www.spring.boot.utils.date.FormatDateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author xct
 * @date 2021/7/30 17:06
 */
@Slf4j
@Data
@Component
public class MqttConsumerCallBack implements MqttCallback {

    /**
	 * 客户端断开连接的回调
	 * @param throwable Throwable
	 * @date 2021/7/30 17:14
	 */
	@Override
	public void connectionLost(Throwable throwable) {
		log.info("MqttConsumerCallBack.connectionLost info, try to reconnect");
	}

	/**
	 * 消息到达的回调
	 * @author xct
	 * @param topic String
	 * @param message MqttMessage
	 * @date 2021/7/30 17:14
	 */
	@Override
	public void messageArrived(String topic, MqttMessage message) {
		try{
			String payload = new String(message.getPayload());
			Date date = new Date(System.currentTimeMillis());
			String dateString = FormatDateUtil.format(date);
			log.info("MqttConsumerCallBack.messageArrived info, topic: {}, payload: {}, date: {}", topic, payload, dateString);
			FormatDateUtil.clearThreadLocal();
		} catch (NullPointerException npe){
			log.error("MqttConsumerCallBack.messageArrived error, 空指针：" + npe.getLocalizedMessage());
		} catch (Exception e){
			log.error("MqttConsumerCallBack.messageArrived error, error info：" + e.getMessage());
		}
	}

	/**
	 * 消息发布成功的回调
	 * @author xct
	 * @param iMqttDeliveryToken IMqttDeliveryToken
	 * @date 2021/7/30 17:14
	 */
	@Override
	public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
		//
		log.info("MqttConsumerCallBack.deliverComplete debug, iMqttDeliveryToken: {}",
				iMqttDeliveryToken.getMessageId()
		);
	}

}
